/*
Copyright 2005-2014 CP Fricano - All Rights Reserved

This software and source code is licensed under the Apache
License, Version 2.0. You may not use this software or source
code except in compliance with the License.  You may obtain a
copy of the License at: http://www.apache.org/licenses/LICENSE-2.0.
Use and distributed under this License is on an "as is" basis,
without expressed or implied warranties or conditions of any kind.
See the License for the specific language governing permissions and
limitations.
 */

package com.fricano.java42.instructional.example.swing;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.InputStream;

import javax.imageio.ImageIO;
import javax.swing.JPanel;

public class J42JPanel_03 extends JPanel {

    private static final long serialVersionUID = -42L;
    private BufferedImage     bufferedImage    = null;
    private BufferedImage     imageRotated     = null;

    public J42JPanel_03() {
        try (
             InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("images/MonaLisa.jpg");) {
            bufferedImage = ImageIO.read(inputStream);
        } catch (final Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void paintComponent(final Graphics g) {
        super.paintComponent(g);
        if (bufferedImage != null && imageRotated == null) {
            g.drawImage(bufferedImage, 0, 0, getWidth(), getHeight(), null);
        }
        else {
            if (imageRotated != null) {
                g.drawImage(imageRotated, 0, 0, getWidth(), getHeight(), null);
            }
        }
    }

    public void doRotate(final int degrees) {
        imageRotated = new BufferedImage(bufferedImage.getWidth(), bufferedImage.getHeight(), bufferedImage.getType());
        final Rectangle rectangle = new Rectangle(0, 0, bufferedImage.getWidth(), bufferedImage.getHeight());
        final Graphics2D g2d = (Graphics2D) imageRotated.getGraphics();
        final AffineTransform affineTransform = new AffineTransform();
        affineTransform.rotate(Math.toRadians(degrees), rectangle.getX() + rectangle.width / 2, rectangle.getY() + rectangle.height / 2);
        g2d.drawImage(bufferedImage, affineTransform, null);
        repaint();
    }

}
